import time
import random

import requests
from lxml import etree
import re

headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8",
    "cache-control": "max-age=0",
    "priority": "u=0, i",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}
cookies = {
    "__uzma": "c633cfc5-48ea-43eb-8bab-ce6c94461ee2",
    "__uzmb": "1753971217",
    "__uzme": "2961",
    "__ssds": "2",
    "__ssuzjsr2": "a9be0cd8e",
    "__uzmaj2": "0a6c63ed-9a39-449c-aa93-577e74fda86a",
    "__uzmbj2": "1753971220",
    "__uzmlj2": "u53RduuRcE/t7/VIYGw6Hcl3FtmJEW6RfTRKu+cY858=",
    "_scid": "-bvR8p6g3mDf3b9xIKThxAzAnXILsg0h",
    "_gcl_au": "1.1.68273251.1753971224",
    "_ScCbts": "%5B%5D",
    "_fbp": "fb.1.1753971225891.219721597686947257",
    "_pin_unauth": "dWlkPU56a3paREJrWVdRdE56azNOUzAwTjJGa0xUZ3labUV0Tldaa01tWmpaRGhsWVRrNQ",
    "__gsas": "ID=5efe9c42859b5330:T=1753971260:RT=1753971260:S=ALNI_MasBWUOVn7dGRtEaRYGGClOW3gkEw",
    "ak_bmsc": "94145F397DDFD94B19BBC86D429BD5C8~000000000000000000000000000000~YAAQhfw7F2tKNmGYAQAAdETMZBzgILl2s+ouhxs3lofJaPrJ2GdelqAaKEHFgmp5ouKwtdruUtSiBxSv6NUPXxLidmweKkcZOVDQmzjBUZOkm34OCPLi1+H0Wkz9sGlfOjPVCnh423zNaMWwRXaITTYSJB+otB1jylV9xCHr+i6+msnFAWFEfDekuISWEn95yI5I0Lc/yJ5UIBzEXpPMqb7vmcVDvnp5S7BkYUSbyAIoZhkCXh6smuxABv9z2zY1Iq2C+4C5TiRzYJHZolhARHTTy45I0zMo5ZQUYul/hTnSp+bvJlLLUEHWP4EMfYtDCPf/6Qrq1bnNVoLKvdPSNkNmpv8oUbQNYqwrHmWFrGIrZb3Jc50YDCdcik6CJSQexC2g7pE=",
    "utag_main__sn": "2",
    "utag_main_ses_id": "1754037764776%3Bexp-session",
    "utag_main__ss": "0%3Bexp-session",
    "__gads": "ID=9940ec38c64a7239:T=1753971222:RT=1754040449:S=ALNI_MZd7XHkk0R5tNdow1aI_Ze0LLgVow",
    "__gpi": "UID=000011734b0dbce0:T=1753971222:RT=1754040449:S=ALNI_MZaDu0E-l-FTqCzIcSrh_JYnb1Ddw",
    "__eoi": "ID=91b68745775da2d2:T=1753971222:RT=1754040449:S=AA-AfjbJi9_HRnPSUi3RXS_J9uqS",
    "s": "CgADuAsNojdpaMTQGaHR0cHM6Ly93d3cuZWJheS5jb20vc3BsYXNodWkvY2hhbGxlbmdlP2FwPTEmYXBwTmFtZT1vcmNoJnJ1PWh0dHBzJTNBJTJGJTJGd3d3LmViYXkuY29tJTJGaXRtJTJGMjI2MzgyOTgzNzM5JTNGX3NrdyUzRGlQaG9uZSUyNmVwaWQlM0QzMDY1MDA0MzgxJTI2aXRtbWV0YSUzRDAxSzFKREdLRVlINDA5UVI2Qk02MEs4OVc1JTI2aGFzaCUzRGl0ZW0zNGI1N2EzMjNiJTNBZyUzQWdWa0FBT1N3MlZka0NkNEklMjZpdG1wcnAlM0RlbmMlMjUzQUFRQUtBQUFBNEZrZ2dGdmQxR0dEdTB3M3lYQ21pMWVWMm02REQ0NHR5VlFaTEY4QjUlMjUyRmJLT3RNOTd4WWxCTnBSMWNaTyUyNTJCWGF5TUltOGo5WFh4d25SdUVRQzVjVUlTUlJNMUpEblNCN3BHaVJ5R2xjcjlsTUhwMFdJU0ZDb1VZY05FY2dRbzVCb1liWUVLdTlRbThHRUpkTjM5MlplMnZNSzBITjAlMjUyRnRIOEdFb3pJV2trTG5ReEpOJTI1MkJpJTI1MkZlZmg1aUl3JTI1MkZCNEYycnBZaDljJTI1MkJ1NFYwR2ZpU0M1T0V0OVFidUVoblFxb0M3N0Z3RUxIclVwQUx1aXJVNTNZNFJEZDVWaXV5Qm5QeHRPcGxsSXdqJTI1MkZ3eklPNEZIWjR0ZDBhVWtONjBxdnNBT2FJYmdJdmh3NThLcG1PVyUyNTJGJTI1N0N0a3AlMjUzQUJGQk0zTGZDell4bSZpaWQ9MzlmYTRiYTQtZjM5MS00YWU3LTk4NWQtZDdiZTNiYzZhNTg4JmlpbT1oTXpVdU5JJmlpYT1ydnpjdU1UeEMmaWl6PXl2SmN1TWpNMWhLbAcA+AAgaI3PhDYwZDRkNTcwMTk4MGFiMWVhOTYyMDQxMWZmZmQ1NjY4FXAopw**",
    "_rdt_uuid": "1753971313524.fcabfab7-cb4b-48b0-b934-97600aad0f11",
    "_uetsid": "c64d66506e1811f0a512330497ddbec3|1d1kwdc|2|fy3|0|2038",
    "_uetvid": "c64d91a06e1811f0bc5d5f498a94248f|1mj45c4|1754040543263|5|1|bat.bing.com/p/insights/c/l",
    "__uzmc": "7541910360841",
    "__uzmd": "1754040599",
    "__uzmf": "7f60004a95d886-d21d-450f-9a21-e38192683662175397121775569381309-b01974494a07f703103",
    "__uzmcj2": "168723187841",
    "__uzmdj2": "1754040600",
    "__uzmfj2": "7f60004a95d886-d21d-450f-9a21-e38192683662175397122003669379989-f5fd4dae798bd72831",
    "utag_main__se": "9%3Bexp-session",
    "utag_main__st": "1754042434299%3Bexp-session",
    "utag_main__pn": "9%3Bexp-session",
    "_scid_r": "9DvR8p6g3mDf3b9xIKThxAzAnXILsg0h65z-FA",
    "cto_bundle": "rOFP9V96WWd1SGpFb1BKaXhxUzFLaUQwUE1xRGZwN0g2UERxVlFibXBqRURFQ1hRR0NoVG1OejlQZFVXcndoTDB1R252eElyTCUyQkc4M000SHV6VEdXdG5JM0xDN2lUWVdENUNOS24zViUyRkoyTk9xbGdxNlgxaHVkOUVPTyUyQmZQN25aRUdVYVp6WEtrJTJCN0FOUktzazVScTVTMFpHZyUzRCUzRA",
    "ebay": "%5Ejs%3D1%5Esbf%3D%23000000%5E",
    "__deba": "JsK19ZP2oV1t25n2r6a3IsBlfL1fiY9lRLPcfP8PwWnAh6zYGUEVE5DM-bt7GwGVIATmry0WA3zen0-5cfBeSV-5CvLAj23fy4zBKbULDd66orXFis72sZS-qm1k0Ll8UsrDtopnxH9OM3wV0F5uRg==",
    "ns1": "BAQAAAZhdx0gSAAaAANgAU2ptvVJjNjl8NjAxXjE3NTM5NzEyMTc4MzdeXjFeM3wyfDV8NHw3fDEwfDQyfDQzfDExXl5eNF4zXjEyXjEyXjJeMV4xXjBeMV4wXjFeNjQ0MjQ1OTA3NfTMpmUwcldNST1LU3tp2c1dSEzq",
    "dp1": "bpbf/%230000002000000000000000006a6dbd52^bl/JPen-US6c4ef0d2^",
    "nonsession": "BAQAAAZhdx0gSAAaAADMACGptvVIxMDAtMDAwMQDKACBsTvDSNjBkNGQ1NzAxOTgwYWIxZWE5NjIwNDExZmZmZDU2NjgAywACaIyQ2jk14CEW8zjTjfKqHIp7inPQStorvnU*"
}
count = 0
for page in range(1, 31):
    url = "https://www.ebay.com/b/Cell-Phones-Smartphones/9355/bn_320094"
    params = {
        "Brand": "Apple|Samsung",
        "LH_ItemCondition": "1000|1500|2010",
        "_pgn": "1",
        "mag": "1",
        "rt": "nc"
    }

    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    html_str = response.content.decode()
    root = etree.HTML(html_str)

    data_list = root.xpath("//ul[@class='brwrvr__item-results brwrvr__item-results--list']/li")
    for data in data_list:
        count += 1
        # 商品链接
        detail_link = "".join(data.xpath(".//span[@class='bsig__title']/a/@href"))
        # 获取品牌，手机状态
        brand_item = "".join(
            data.xpath(".//span[@class='textual-display bsig__generic bsig__listingCondition']//span/text()"))
        brand_str = re.sub(r'\s*[·.-]\s*', " ", brand_item)
        # 定义提取规则
        pattern = r'(Open Box)|(Brand New)|(Refurbished)'
        # 提取结果
        match = re.search(pattern, brand_str)
        if match:
            # 取第一个匹配到的非空分组
            result = next(group for group in match.groups() if group is not None)
            # 简化结果（如果需要只保留核心词）
            condition = result.replace("Brand ", "").strip()
        brand = re.split(" ", brand_str)[-1]
        # print(brand_str)
        title = "".join(data.xpath(".//span[@class='bsig__title']/a/h3/text()"))

        print(f"{count}, 品牌:{brand}, 标题:{title}, 商品状态:{condition}, 链接{detail_link}")

    time.sleep(random.randint(1, 2))
